package com.jingbian.cppccbackend.service.impl.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.ProposalAttachments;
import com.jingbian.cppccbackend.entity.ProposalSigners;
import com.jingbian.cppccbackend.entity.Proposals;
import com.jingbian.cppccbackend.entity.dto.ProposalSignersListDTO;
import com.jingbian.cppccbackend.mapper.user.ProposalAttachmentsMapper;
import com.jingbian.cppccbackend.mapper.user.ProposalSignersMapper;
import com.jingbian.cppccbackend.mapper.user.ProposalsMapper;
import com.jingbian.cppccbackend.service.user.IProposalSignersService;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import com.jingbian.cppccbackend.vo.ProposalSignersListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 提案联名人表 服务实现类
 * </p>
 *
 * @author pum
 * @since 2025-02-12
 */
@Service
public class ProposalSignersServiceImpl extends ServiceImpl<ProposalSignersMapper, ProposalSigners> implements IProposalSignersService {
  @Autowired
  public ProposalSignersMapper proposalSignersMapper;
  @Autowired
  public ProposalsMapper proposalsMapper;
  @Autowired
  private ProposalAttachmentsMapper proposalAttachmentsMapper;

  @Override
  public PageInfo<ProposalSignersListVO>  getList(ProposalSignersListDTO proposalSignersListDTO) {
    // 开启分页
    PageHelper.startPage(proposalSignersListDTO.getPageNum(), proposalSignersListDTO.getPageSize());
    Map<String, Object> claims = ThreadLocalUtil.get();
    proposalSignersListDTO.setUserId((Integer) claims.get("uid"));
    // 执行查询，使用原有的mapper方法
    List<ProposalSignersListVO> list = proposalSignersMapper.getSignerList(proposalSignersListDTO);

    // 将结果封装成PageInfo对象
    return new PageInfo<>(list);
  }

  @Override
  public ProposalSigners changeStatus(Integer id, String status) {
    Map<String, Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("uid");
    UpdateWrapper<ProposalSigners> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("proposal_id", id)
            .eq("user_id", userId);
    updateWrapper.set("dispose_status", status);
    proposalSignersMapper.update(null, updateWrapper);
    QueryWrapper<ProposalSigners> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("proposal_id", id)
            .eq("user_id", userId);

    LambdaQueryWrapper<ProposalSigners> selectWrapper = new LambdaQueryWrapper<>();
    selectWrapper.eq(ProposalSigners::getProposalId,id).eq(ProposalSigners::getDisposeStatus,"未处理");
    // 执行查询
    List<ProposalSigners> signers = proposalSignersMapper.selectList(selectWrapper);
    // 判断查询结果是否为空
    // 当查询结果为空时，执行更新操作
//    if (signers.isEmpty()&&!status.equals("拒绝")) {
//      LambdaUpdateWrapper<Proposals> updateWrapper1 = new LambdaUpdateWrapper<>();
//      updateWrapper1
//              .set(Proposals::getIsOr, true)          // 设置 isOr = true
//              .ne(Proposals::getIsOr, false)           // 仅当 isOr 不是 false 时更新
//              .eq(Proposals::getPid, id);               // 限定当前提案ID对应的记录
//      // 执行更新，并返回受影响的行数
//      proposalsMapper.update(null, updateWrapper1);
//    }
    if (signers.isEmpty()&&!status.equals("拒绝")) {
      System.out.println("执行true");
      LambdaUpdateWrapper<Proposals> updateWrapper1 = new LambdaUpdateWrapper<>();
      updateWrapper1
              .set(Proposals::getIsOr, true)
              .set(Proposals::getIsOrTime, LocalDateTime.now()) // 设置联名通过时间为当前时间
              .eq(Proposals::getPid, id)
              .and(wrapper -> wrapper
                      .ne(Proposals::getIsOr, false)
                      .or()
                      .isNull(Proposals::getIsOr)
              );
      // 执行更新，并返回受影响的行数
      proposalsMapper.update(null, updateWrapper1);
    }
    if (status.equals("拒绝")){
      LambdaUpdateWrapper<Proposals> updateWrapper1 = new LambdaUpdateWrapper<>();
      updateWrapper1
              .set(Proposals::getIsOr, false)          // 设置 isOr = true
              .eq(Proposals::getPid, id);               // 限定当前提案ID对应的记录
      // 执行更新，并返回受影响的行数
      proposalsMapper.update(null, updateWrapper1);
    }
    return proposalSignersMapper.selectOne(queryWrapper);
  }

  @Transactional
  @Override
  public Integer deleteConsignProposals(Integer proposalId) {
    /**
     * 返回1，则表示提案不存在
     * 返回2，则表示与用户id不一致
     * 返回3，提案已过初审的申请
     * 返回4，提案删除成功！1
     */
    QueryWrapper<Proposals> wrapper = new QueryWrapper<>();
    wrapper.eq("pid",proposalId);
    Proposals proposals = proposalsMapper.selectOne(wrapper);
    if(proposals == null) {
      return 1;
    }
    Map<String, Object> claims = ThreadLocalUtil.get();
    Integer uid = (Integer)claims.get("uid");
    if (!proposals.getUserId().equals(uid)){
      return 2;
    }

    if ( Objects.nonNull(proposals.getIsOr())&&proposals.getIsOr()){
      return 3;
    }

    /**
     * 进行提案联名的联名人待处理或已处理的事项进行删除操作。
     */
    LambdaQueryWrapper<ProposalSigners> wrapper1 = new LambdaQueryWrapper<>();
    wrapper1.eq(ProposalSigners::getProposalId, proposalId);
    proposalSignersMapper.delete(wrapper1);
    /**
     *
     * 针对于附件表进行删除操作。
     */
    LambdaQueryWrapper<ProposalAttachments> wrapper2 = new LambdaQueryWrapper<>();
    wrapper2.eq(ProposalAttachments::getProposalId, proposalId);
    proposalAttachmentsMapper.delete(wrapper2);
    /**
     * 对于提案表进行删除操作。
     */
    proposalsMapper.delete(wrapper);
    return 4;
  }
}
